// npm install axios
const axios = require('axios');
const fs = require('fs');
const path = require('path');

//================================  插件网址和版本信息
const _inputString = 'https://marketplace.visualstudio.com/items?itemName=ms-vscode.cmake-tools';
// 版本号
const _version = "1.21.2";


// //================================ 解析和下载
const version = _version.trim();
// 提取 "?itemName=" 后面的 "ms-vscode.cmake-tools"
const itemNameMatch = _inputString.trim().match(/\?itemName=([a-zA-Z0-9.-]+)/);
if (!itemNameMatch) {
    console.error("无法提取 itemName");
    process.exit(1);
}

const itemName = itemNameMatch[1]; // "ms-vscode.cmake-tools"
const [publisher, extensionName] = itemName.split('.'); // 分割成 "ms-vscode" 和 "cmake-tools"
// 设置输出文件路径
const _outputFilePath = path.join(__dirname, `${itemName}-${version}.vsix`);


// 构造新的 URL
const newUrl = `https://marketplace.visualstudio.com/_apis/public/gallery/publishers/${publisher}/vsextensions/${extensionName}/${version}/vspackage`;
// 构造新的字符串
const newString = `<url id="cv5bfq8pe77nvqvdon90" type="url" status="failed" title="" wc="0">${newUrl}</url>`;
console.log("构造的 URL:\n", newUrl);

// 下载文件
async function downloadFile(url, outputPath) {
    try {
        const response = await axios.get(url, {
            responseType: 'stream' // 以流的形式处理响应内容
        });

        // 检查响应状态码
        if (response.status === 200) {
            // 创建输出流
            const writer = fs.createWriteStream(outputPath);

            // 将响应流写入文件
            response.data.pipe(writer);

            return new Promise((resolve, reject) => {
                writer.on('finish', resolve);
                writer.on('error', reject);
            });
        } else {
            console.error(`下载失败，状态码: ${response.status}`);
            process.exit(1);
        }
    } catch (error) {
        console.error("下载过程中发生错误:", error.message);
        process.exit(1);
    }
}



// 调用下载函数
downloadFile(newUrl, _outputFilePath)
    .then(() => {
        console.log(`文件已成功下载到: ${_outputFilePath}`);
    })
    .catch((error) => {
        console.error("下载失败:", error);
    });